
package com.ce.cases.source.action;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.ce.cases.report.logic.IReportIllegalLogic;
import com.ce.cases.source.dao.po.CaseSource;
import com.ce.cases.source.dao.po.CaseSourceApprove;
import com.ce.cases.source.dao.po.CaseSourceDrawApprove;
import com.ce.cases.source.dao.po.CaseSourceFiles;
import com.ce.cases.source.dao.po.DjNsrxx;
import com.ce.framework.constants.WebConstants;
import com.ce.framework.datamaintain.action.DataMaintainAction;
import com.ce.framework.datamaintain.dao.po.AbstractPO;
import com.ce.framework.exception.AppException;
import com.ce.framework.util.BeanAccessUtil;
import com.ce.framework.util.DateUtil;
import com.ce.framework.util.GeneratorUUID;
import com.ce.framework.util.LogUtil;
import com.ce.framework.util.StringUtil;
import com.ce.framework.util.node.JsonTreeNode;
import com.ce.sys.login.model.User;
import com.ce.sys.org.dao.po.SysVOrg;
import com.ce.sys.person.dao.po.SysPerson;
import com.ce.util.DbUtil;
import com.ce.util.FlowPicView;
import com.ce.util.FlowWorkUtil;
import com.ce.util.OrgUtil;
import com.ce.workflow.work.dao.po.WorkflowFlow;
import com.ce.workflow.work.dao.po.WorkflowWork;


/**
* 嫦娥软件有限公司 版权所有 2013
* 创建人：　andy
* 创建日期：2014-03-18
* 创建时间：15:29:27
* 功能描述：备选案源台账 [CASE_SOURCE]更改时用的Action
* ==============================================
* 修改历史
* 修改人		修改时间		修改原因
*
* ==============================================
*/
public class CaseSourceAction extends DataMaintainAction 
{
	private static final long serialVersionUID = 1L;
	
	private CaseSourceApprove appr;
	private CaseSourceDrawApprove drawAppr;
	private IReportIllegalLogic reportIllegalLogic;
	@Override
	protected void initOtherData(boolean isNew) {
		if(isNew){
			try {
				BeanAccessUtil.copyProperty(po, "registerPerson", User.getUserName());
				BeanAccessUtil.copyProperty(po, "registerDate", new Date());
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			
		}
	}
	
	public String openTqPage(){
		initOtherData(true);
		try {
			return this.add();
		} catch (AppException e) {
			e.printStackTrace();
		}
		return "";
	}
	@Override
	protected String addItem() throws AppException {
		String inspectionDeptId=this.getParameter("po.inspectionDeptId");
		String collectionDeptId=this.getParameter("po.collectionDeptId");
		String jcjName=OrgUtil.getOrgName(inspectionDeptId);
		String zgjName=OrgUtil.getOrgName(collectionDeptId);
		try {
			if("2".equals(User.getUser().getRootOrgLevel()))//市局
				BeanAccessUtil.copyProperty(po, "vcType", "1");//市局录入
			else
				BeanAccessUtil.copyProperty(po, "vcType", "2");//跨区局提请
			BeanAccessUtil.copyProperty(po, "registerDeptId", User.getUserOrgId());
			BeanAccessUtil.copyProperty(po, "registerDept", User.getUserOrgName());
			BeanAccessUtil.copyProperty(po, "vcAaccept", "1");
			BeanAccessUtil.copyProperty(po, "state", "0");
			BeanAccessUtil.copyProperty(po, "stateInfo", "备选案源");
			BeanAccessUtil.copyProperty(po, "inspectionDept", jcjName);
			BeanAccessUtil.copyProperty(po, "collectionDept", zgjName);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return super.addItem();
	}
	@Override
	protected String modifyItem() throws AppException {
		//避免将流程状态暴漏给页面，避免非法篡改
		CaseSource entiy=(CaseSource)this.baselogic.getPOByPk(po.getClass().getName(), po.getVcId());
		BeanAccessUtil.copyNoCopyNullProperty(po, entiy);
		CaseSource po2=(CaseSource)po;
		String jcjName=OrgUtil.getOrgName(po2.getInspectionDeptId());
		String zgjName=OrgUtil.getOrgName(po2.getCollectionDeptId());
		entiy.setInspectionDept(jcjName);
		entiy.setCollectionDept(zgjName);
		this.baselogic.updatePo(entiy,this.getAddList(),this.getModifyList(),this.getDeleteList());
	    return super.searchData();			
	}
	@Override
	public String look() throws AppException {
		super.look();
		return WebConstants.REQUEST_LOOKDATA_OPERATOR;
	}
	public String openShPage(){
		return "openShPage";
	}
	
	/**
	 * 重新受理
	 * @return
	 */
	public String saveNewAcceptSuccessed(){
		String[] vcIds=this.getParameterValues("chkSelf[]");
		String acceptType=this.getParameter("acceptType");//是否受理
		//CaseSource po=new CaseSource();
		User user=User.getUser();
		
		String sql_ids=StringUtil.fromArrayToStr(vcIds, true);
		
		List<CaseSource> l=new ArrayList<CaseSource>();
		try {
			l = (List<CaseSource>)this.baselogic.searchByHql("FROM CaseSource p where p.vcDelFlag='0' and p.vcId in("+sql_ids+")");
		} catch (AppException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		if(l!=null&&l.size()>0){
			for(CaseSource p:l){
				List<CaseSourceDrawApprove> ll=new ArrayList<CaseSourceDrawApprove>();
				try {
					ll=(List<CaseSourceDrawApprove>)this.baselogic.searchByHql("FROM CaseSourceDrawApprove p where p.caseId='"+po.getVcId()+"' and p.vcDelFlag='0'");
				} catch (AppException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if(ll!=null&&ll.size()>0){
					CaseSourceDrawApprove approvePo=ll.get(0);
					approvePo.setVcAaccept(acceptType);//2未受理 1已受理
					try {
						this.baselogic.updatePo(approvePo);
					} catch (AppException e) {
						e.printStackTrace();
					}
				}				
				p.setVcAaccept(acceptType);		
				try {
					this.baselogic.updatePo(p);
				} catch (AppException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}		
				FlowWorkUtil.saveWorkflowMan(p.getVcId(), "重新受理");
			}
		}
		
		return this.returnInfoForJS(true, "操作成功！");
	}
	
	public String openSubmitPage(){
		
		String vcId=this.getParameter("chkSelf");
		
		CaseSource po=null;
		try {
			po = (CaseSource) this.baselogic.getPOByPk(CaseSource.class.getName(), vcId);
		} catch (AppException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(1==po.getState()){
			return this.alertMsgAndExecJs("不能重复操作，该案源已上报！", "$('#operateWindow').window('close');");
		}
		List<SysPerson> persons=OrgUtil.getUserByOrgId("15009070700", true);
		this.setAttribute("persons", persons);
		this.setAttribute("vcId", vcId);
		return "caseSourceSubmit";
	}
	
	public String submitSuccessed(){
		String vcRecordId=this.getParameter("chkSelf");
		String vcHandlePersonId=this.getParameter("vcHandlePersonId");
		String vcHandlePersonName=this.getParameter("vcHandlePersonName");
		CaseSource po=new CaseSource();
		User user=User.getUser();
		try {
			po=(CaseSource)this.baselogic.getPOByPk(po.getClass().getName(), vcRecordId);
		} catch (AppException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		po.setState(1);//上报到分管局长
		po.setStateInfo("已上报分管局长。");		
		
		String vcHandleOrgId="",vcHandleOrgName="";
		String vcDesc=this.getParameter("vcAdvance");		
		vcHandleOrgId=OrgUtil.getOrgIdByUserId(vcHandlePersonId);
		vcHandleOrgName=OrgUtil.getOrgNameByUserId(vcHandlePersonId);
		FlowWorkUtil.submitFlowWork("CASE_SOURCE",vcRecordId,"1",user.getVcOrgId(),user.getOrgName(),user.getVcId(),user.getVcName(), vcHandleOrgId, vcHandleOrgName, vcHandlePersonId, vcHandlePersonName, vcDesc);			
		try {
			this.baselogic.updatePo(po);
		} catch (AppException e) {
			e.printStackTrace();
		}
		
		return this.returnInfoForJS(true, null);		
	}
	
	public String lookItemFrame(){
		return "lookItemFrame";
	}
	public void wsTree(){
		String vcRecordId=this.getParameter("vcRecordId");
		String hql="from CaseSourceFiles t where t.vcRecordId='"+vcRecordId+"' order by t.dtDate";
		List<CaseSourceFiles>  files=new ArrayList<CaseSourceFiles>();
		try {
			files=(List<CaseSourceFiles>) this.baselogic.searchByHql(hql);
		} catch (AppException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		JSONArray jsonTree = new JSONArray();
		List<JsonTreeNode> fileList = new ArrayList<JsonTreeNode>();
		JsonTreeNode rootNode=new JsonTreeNode();
		rootNode.setId("1");
		rootNode.setIconCls("ext-icon-book_open");
		rootNode.setText("案源文书");
		rootNode.setState("open");
		if(files!=null&&files.size()>0){
			for(CaseSourceFiles file:files){
				JsonTreeNode child = new JsonTreeNode();
            	child.setId(file.getVcFileId());
            	child.setText(file.getVcFileName());
            	child.setIconCls("ext-icon-book_open");
            	fileList.add(child);
			}
			rootNode.setChildren(fileList);
		}
		List<JsonTreeNode> nodeList = new ArrayList<JsonTreeNode>();
		nodeList.add(rootNode);
		jsonTree.add(nodeList); // 写入树节点信息
		// 以字符串为文件流进行输出
		// 由于形成的json格式与easyui的格式在外部多了个[]，因此在这里进行移除。
		writeHTML(jsonTree.toString().substring(1, jsonTree.toString().length() - 1).toString()); // 将树以JSON格式的字符串进行输出

		
	}
	
	public String ajaxPersons(){
		String vcOrgId=this.getParameter("vcOrgId");
		List<SysPerson> persons=OrgUtil.getUserByOrgId(vcOrgId, true);
		this.rows=persons;
		return JSON;
	}
	public String ajaxOrgs(){
		String vcOrgId=this.getParameter("vcOrgId");
		List<SysVOrg> orgs=OrgUtil.getChildDep(vcOrgId);
		this.rows=orgs;
		return JSON;
	}
	/**
	 * 案源退回界面
	 * @return
	 */
	public String caseSourceGoBack(){
		return "caseSourceGoBack";
	}
	
	
	/**
	 * 打开案源下发界面
	 * @return
	 */
	public String caseSourceDown(){
		String vcId=this.getParameter("chkSelf");
		String vcParId=User.getParOrgIdByOrgLevel("1");
		List<SysVOrg> deps=OrgUtil.getChildPro(vcParId);
		StringBuffer op = new StringBuffer();
		if(deps!=null&&deps.size()>0){
			for(SysVOrg org:deps){
				    op.append("<option value='"+org.getVcId()+"'>"+org.getVcName()+"</option>");
			}
			
		}else{
			op.append("<option value=''></option>");
		}
		this.setAttribute("deps", deps);
		this.setAttribute("vcId", vcId);
		return "caseSourceDown";
	}
	//
	public String caseSourceDownSuccess(){
		String vcRecordId=this.getParameter("chkSelf");
		String handOverId=this.getParameter("handOverId");
		String handOverName=this.getParameter("handOverName");
		String vcHandleOrgId="",vcHandleOrgName="",vcHandlePersonId="",vcHandlePersonName="";
//		String vcHandleOrgName=OrgUtil.getOrgName(vcHandleOrgId);
//		String vcHandlePersonId=this.getParameter("handOverPersonId");
//		String vcHandlePersonName=this.getParameter("handOverPerson");
		String vcDesc=this.getParameter("vcAdvance");
		String vcType=this.getParameter("vcType");
//		if("1".equals(vcType)){//下发到人员
//			vcHandlePersonId=handOverId;
//			vcHandlePersonName=handOverName;
//			vcHandleOrgId=OrgUtil.getOrgIdByUserId(vcHandlePersonId);
//			vcHandleOrgName=OrgUtil.getOrgNameByUserId(vcHandlePersonId);
//			FlowWorkUtil.setFlowWork("T_WORKFLOW_WORK", vcRecordId,vcType,User.getUserOrgId(),User.getUserOrgName(),User.getUserId(),User.getUserName(), vcHandleOrgId, vcHandleOrgName, vcHandlePersonId, vcHandlePersonName, vcDesc);
//		}else{
//			vcHandleOrgId=handOverId;
//			vcHandleOrgName=handOverName;
//			FlowWorkUtil.setFlowWork("T_WORKFLOW_WORK", vcRecordId,vcType,User.getUserOrgId(),User.getUserOrgName(),User.getUserId(),User.getUserName(), vcHandleOrgId, vcHandleOrgName, vcHandlePersonId, vcHandlePersonName, vcDesc);
//		}
			
		
		return this.returnInfoForJS(true, null);
	}
	
	/*
	 * 处理审批页面
	 */
	public String dealApprovePage() throws AppException{
		String caseId=this.getParameter("caseId");
		CaseSource source=(CaseSource)this.baselogic.getPOByPk("com.ce.cases.source.dao.po.CaseSource", caseId);
		List approveList=this.baselogic.searchByHql("From CaseSourceApprove po where po.caseId='"+caseId+"' and po.vcDelFlag=0");
		if(!approveList.isEmpty()){
			appr=(CaseSourceApprove)approveList.get(0);
		}else{
			appr=new CaseSourceApprove();
			appr.setCaseId(source.getVcId());
			appr.setCaseFrom(source.getCaseFromName());
			appr.setCaseNum(source.getCaseNumber());
			appr.setInvolvedEnterprice(source.getInvolvedEnterprice());
			appr.setTaxpayerNumber(source.getTaxpayerNumber());
		}
		return "dealApprovePage";
	}
	
	/*
	 * 处理审批操作
	 */
	public String dealApprove() {
		try {
			// 修改审批表
			if (StringUtil.isNotBlank(appr.getVcId())) {
				appr.setVcDelFlag(0);
				this.baselogic.updatePo(appr);
			} else {// 添加审批表
				appr.setVcId(GeneratorUUID.generateUUID());
				appr.setVcDelFlag(0);
				this.baselogic.addPo(appr);
			}
		} catch (AppException e) {
			LogUtil.logError(e);
			return this.returnInfoForJS(false,
					e.getMessage().replaceAll("'|\\n", " "));
		}
		return this.returnInfoForJS(true, null);
	}
	
	/*
	 * 提请审批页面
	 */
	public String drawApprovePage() throws AppException{
		String caseId=this.getParameter("caseId");
		CaseSource source=(CaseSource)this.baselogic.getPOByPk("com.ce.cases.source.dao.po.CaseSource", caseId);
		List drawApprList=this.baselogic.searchByHql("From CaseSourceDrawApprove po where po.caseId='"+caseId+"' and po.vcDelFlag=0");
		if(!drawApprList.isEmpty()){
			drawAppr=(CaseSourceDrawApprove)drawApprList.get(0);
		}else{
			drawAppr=new CaseSourceDrawApprove();
			drawAppr.setCaseId(caseId);
			drawAppr.setCaseFromNum(source.getCaseFromNum());
			drawAppr.setCaseFromName(source.getCaseFromName());
			drawAppr.setTaxpayer(source.getInvolvedEnterprice());
			drawAppr.setTaxpayerNumber(source.getTaxpayerNumber());
			drawAppr.setDrawDept(User.getUserOrgName());
			drawAppr.setDrawDeptId(User.getUserOrgId());
			drawAppr.setInspectionDept(source.getInspectionDept());
			drawAppr.setInspectionDeptId(source.getInspectionDeptId());
			drawAppr.setCollectionDept(source.getCollectionDept());
			drawAppr.setCollectionDeptId(source.getCollectionDeptId());
			drawAppr.setIllegalTypeNum(source.getIllegalTypeNum());
			drawAppr.setIllegalTypeName(source.getIllegalTypeName());
		}
		return "drawApprovePage";
	}
	
	/*
	 * 提请审批操作
	 */
	public String drawApprove() throws AppException{
		try {
			// 修改审批表
			if (StringUtil.isNotBlank(drawAppr.getVcId())) {
				drawAppr.setVcDelFlag(0);
				this.baselogic.updatePo(drawAppr);
			} else {// 添加审批表
				drawAppr.setVcId(GeneratorUUID.generateUUID());
				drawAppr.setVcDelFlag(0);
				drawAppr.setDrawDeptId(User.getUserOrgId());
				this.baselogic.addPo(drawAppr);
			}
		} catch (AppException e) {
			LogUtil.logError(e);
			return this.returnInfoForJS(false,
					e.getMessage().replaceAll("'|\\n", " "));
		}
		return this.returnInfoForJS(true, "提请审批操作成功!");
	}
	public String getNsrinfoByTaxpayerNumber(){
    	String taxpayerNumber=this.getParameter("taxpayerNumber");
    	DjNsrxx po=reportIllegalLogic.getDjNsrxxRemote(taxpayerNumber);
    	
    	if(null!=po){
    		SysVOrg jcjorg=OrgUtil.getParOrg(po.getZgswjDm());
    		if(jcjorg!=null){
    			po.setZgswjMc(OrgUtil.getOrgName(po.getZgswjDm()));
            	po.setJcjdm(jcjorg.getVcId());
            	po.setJcjmc(jcjorg.getVcName());
            	String year=DateUtil.getYear();
            	String sql="select count(*) from CASE_SOURCE t where t.INSPECTION_DEPT_ID='"+jcjorg.getVcId()+"' and t.vc_del$flag='0'";
            	int cnt=DbUtil.getFirstIntSqlQuery(sql);
            	String cnt_="";
            	if(cnt<10)
            		cnt_="00"+cnt;
            	else if(cnt<100)
            		cnt_="0"+cnt;
            	else 
            		cnt_=""+cnt;
            	po.setStatusInfo(year+"DX-J"+jcjorg.getNseq()+"-"+cnt_);//待选案源编号
    		}else{
    			return this.returnInfoForJS(false, "对不起，纳税人所属征管局信息错误，请登陆核心征管确认纳税人所属征管局是否正确.");
    		}
    		return writeHTML(JSONObject.fromObject(po).toString());
        	
    	}
    	else
    		return this.returnInfoForJS(false, "对不起，没有获取到纳税人信息，请确认输入的纳税人编号是否正确,或者查询核心征管系统确认该纳税人编号是否存在.");
    }
	public CaseSourceApprove getAppr() {
		return appr;
	}
	public void setAppr(CaseSourceApprove appr) {
		this.appr = appr;
	}
	public CaseSourceDrawApprove getDrawAppr() {
		return drawAppr;
	}
	public void setDrawAppr(CaseSourceDrawApprove drawAppr) {
		this.drawAppr = drawAppr;
	}
	public void setReportIllegalLogic(IReportIllegalLogic reportIllegalLogic) {
		this.reportIllegalLogic = reportIllegalLogic;
	}

}

